// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;


@ccclass
export default class NewClass extends cc.Component {
    小车:cc.Node=null
    Carscript=null
    最大速度:number=2
    onLoad() {
        this.node.on("touchstart", this.onTouchStart, this)
        this.node.on("touchmove", this.onTouchMove, this)
        this.node.on("touchend", this.onTouchEnd, this)
        this.node.on("touchcancel", this.onTouchCancel, this)
        this.小车=cc.find("Canvas/小车")
        this.Carscript=this.小车.getComponent("car")
        
    }
    onTouchStart() {
       this.持续加速()
    }
    持续加速(){
        this.schedule(this.加速,0.1)
    }
    加速(){
      
        if(this.Carscript.speed>this.最大速度){
            this.Carscript.speed-=0.2
            // this.Carscript.speed=this.最大速度
            // this.unschedule(this.加速)
        }else{
            this.Carscript.speed+=0.2
        }
    }
    onTouchMove(e: cc.Event.EventTouch) {
        let parent: cc.Node = this.node.parent
        let pos: cc.Vec2 = parent.convertToNodeSpaceAR(e.getLocation())//转换为本地坐标
        this.node.setPosition(pos)
        //    方位(cos,sin)
        let 方位: cc.Vec2 = pos.normalize()
        let maxR = 64
        let r: number = cc.Vec2.distance(pos, cc.v2(0.0)) 
        if (r > maxR) {
            pos.x = maxR * 方位.x
            pos.y = maxR * 方位.y
            this.node.setPosition(pos)
        }
        let radian=pos.signAngle(cc.v2(1,0))
        let angle=radian/Math.PI*180
        this.小车.angle=-angle
        this.Carscript.direction=方位
    }
    持续减速(){
        this.unschedule(this.加速)
        this.schedule(this.减速,0.1)
    }
    onTouchEnd() {
        this.node.setPosition(cc.v3(0,0,0))
       this.持续减速()
    }
    减速(){
        
        this.Carscript.speed-=0.5
        if(this.Carscript.speed<=0){
            this.Carscript.speed=0
            this.unschedule(this.减速)
        }
    }
    onTouchCancel() {
        this.node.setPosition(cc.v3(0,0,0))
       this.持续减速()
    }
    start() {

    }

}
